package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Service
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {
    /**
     * 过滤器好像是责任链，不太清楚
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //先排除掉不用过滤得url
        String path = request.getURI().getPath();
        if(path.contains("/login"))
        {
            return chain.filter(exchange);
        }
        //获取一个对象，不要集合，所以用first
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.isEmpty("token"))
        {
            //没有token直接送走
         response.setStatusCode(HttpStatus.UNAUTHORIZED);
         return response.setComplete();
        }
        try {
            //验证token是否合法,这里不确定要不要吞异常，好像全局异常捕获得话他也登录不了
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int result = AppJwtUtil.verifyToken(claims);
            if(result==0||result==-1)
            {
                //token还未过期,感觉可以写一个方法，重新刷新token里面的时间戳，可能之后放redis，所以这里就先这样
                request.mutate().header("userId",claims.get("userId").toString());
                request.mutate().header("userName",claims.get("userName").toString());
                //让next过滤器干活
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.setRawStatusCode(401);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
